/*
The MIT License (MIT)

Copyright (c) 2013 Mike Dapiran, Brian May, Richard Pospesel, and Bert Wierenga

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software 
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#pragma once

#include "IList.h"
#include <cmath>

namespace Hogshead
{
	namespace Common
	{
		class Exception;
		template<typename T> class LinkedListEnumerator;	// forward declare
		/**
		* LinkedList<T> is a generic collection implemented as a doubly linked list.  It contains
		* a head and a tail node as well as a current node.  Calling next and previous increments and decrements
		* the index of the current node, so we can get every element of the array in O(1) time using the hasNext() and
		* hasPrevious() methods.  Calling next() and previous() changes the location of the current node.  LinkedList<T>
		* should NOT be used for applications which require a lot of random access.
		*
		* Implements the List<T> interface so you can use the [] subscript operators and whatever else is available there.
		* Sort and Shuffle are not imnplemented and throw exceptions when called.
		*/
		template<typename T> class LinkedList : public IList<T>
		{
		private:
			template<typename S> struct Node;	// forward declare
		public:

			/**
			* Default constructor creates an empty list and sets the various pointers to NULL.
			*/
			LinkedList()
			{
				_head = NULL;
				_tail = NULL;
				_size = 0;
			}
			/**
			* Destructor destroys all of the node objects, but not the contents.
			*/
			~LinkedList()
			{
				clear();
			}
			
			/**
			* Add a new node with the passed in value to the end of the linked list.
			* @param in_t The value to add to the end
			*/
			void add(T in_t)
			{
				if(_head == NULL)
				{
					_head = new Node<T>(in_t);
					_tail = _head;
					_size = 1;
				}
				else if(_size == 1)
				{
					_tail = new Node<T>(in_t);
					_head->next = _tail;
					_tail->previous = _head;
					_size = 2;
				}
				else
				{
					_tail->next = new Node<T>(in_t);
					_tail->next->previous = _tail;
					_tail = _tail->next;
					_size++;
				}
			}

			/**
			* Insert a new T at a specified index.  This method does not change the current node.
			* @param in_index The index of the value to be added
			* @param in_t The value to insert
			*/
			void insert(int in_index, T in_t)
			{
				// first error check
				if(in_index >= _size && in_index < 0)
					throw Exception("Index out of bounds");

				Node<T>* inserted = new Node<T>(in_t);

				if(in_index == 0)	// inserting to head position
				{
					inserted->next = _head;
					_head->previous = inserted;
					_head = inserted;
				}
				else if(in_index == _size - 1)
				{
					inserted->previous = _tail;
					_tail->next = inserted;
					_tail = inserted;
				}
				else
				{
					Node<T>* insertion_point = get_node(in_index);

					// now insertion_point is where we want to insert a new one, inserted is the new one
					inserted->next = insertion_point;
					inserted->previous = insertion_point->previous;
					inserted->next->previous = inserted;
					inserted->previous->next = inserted;
				}
				_size++;
			}
			/**
			* Deletes all of the Node<T> objects, but not the data.  Sets
			* head, current and tail to NULL.
			*/
			void clear()
			{
				Node<T>* current = _tail;
				for(int k = 0; k < _size; k++)
				{
					Node<T>* temp = current->previous;
					delete current;
					current = temp;
				}

				_head = NULL;
				_tail = NULL;
				_size = 0;
			}
			/**
			* Returns a copy of the value found at the passed index.
			* @param in_index The location of the value to return.
			* @return A copy of the value at the passed index.
			*/
			T get(int in_index) const
			{
				// first error check
				if(in_index >= _size && in_index < 0)
					throw Exception("Index out of bounds");
				Node<T>* n = get_node(in_index);
				return n->value;
			}
			/**
			* Returns a reference to the value found at the passed index.
			* @param in_index The location of the value to return.
			* @return A reference the value at the passed index.
			*/
			T& get(int in_index)
			{
				// first error check
				if(in_index >= _size && in_index < 0)
					throw Exception("Index out of bounds");
				Node<T>* n = get_node(in_index);
				return n->value;
			}
			/**
			* Returns a copy of the value at the front of the LinkedList<T>
			*/
			T first() const
			{
				if(_head != NULL)
					return _head->value;
				throw Exception("LinkedList<T> does not contain a head Node");
			}
			/**
			* Returns a reference to the value at the front of the LinkedList<T>.
			*/
			T& first()
			{
				if(_head != NULL)
					return _head->value;
				throw Exception("LinkedList<T> does not contain a head Node");
			}
			/**
			* Returns a copy of the value at the end of the LinkedList<T>.
			*/
			T last() const
			{
				if(_tail != NULL)
					return _tail->value;
				throw Exception("LinkedList<T> does not contain a tail Node");
			}
			/**
			* Returns a reference to the value at the end of the LinkedList<T>.
			*/
			T& last()
			{
				if(_tail != NULL)
					return _tail->value;
				throw Exception("LinkedList<T> does not contain a tail Node");
			}
			/**
			* Removes and returns a copy of the value at the passed in index.
			* @param in_index The index of the value to remove.
			* @return The value found at in_index.
			*/
			T removeAt(int in_index)
			{
				Node<T>* removed = NULL;

				if(in_index == 0)	// removing head
				{
					removed = _head;
					_head = _head->next;
					_head->previous = NULL;
				}
				else if(in_index == _size - 1) // removing tail
				{
					removed = _tail;
					_tail = removed->previous;
					_tail->next = NULL;
				}
				else // removing somewhere in the middle
				{
					removed = get_node(in_index);
					Node<T>* p = removed->previous;
					Node<T>* n = removed->next;
					
					p->next = n;
					n->previous= p;
				}

				T result = removed->value;
				delete removed;
				_size--;
				return result;
			}

			/**
			* Sets the given value at the specified index.
			* @param in_index Location to store passed in value.
			* @param in_t Value to store at in_index.
			*/
			void set(int in_index, T in_t)
			{
				// first error check
				if(in_index >= _size && in_index < 0)
					throw Exception("Index out of bounds");

				Node<T>* n = get_node(in_index);
				n->value = in_t;
			}

			/**
			* Not implemented in LinkedList<T>, throws exception.
			*/
			void shuffle()
			{
				throw Exception("shuffle() not implemented for LinkedList<T>");
			}

			/**
			* Returns the number of elements in the LinkedList<T>
			*/
			int size() const
			{
				return _size;
			}

			/**
			* Not implemented in LinkedList<T>, throws exception.
			*/
			void sort()
			{
				throw Exception("sort() not implemented for LinkedList<T>");
			}

			/**
			* Swaps the values at the two indeces.
			*/
			void swap(int in_left, int in_right)
			{
				Node<T>* left_n = get_node(in_left);
				Node<T>* right_n = get_node(in_right);

				T temp_t = left_n->value;
				left_n->value = right_n->value;
				right_n->value = temp_t;
			}
			
			IEnumerator<T>* getEnumerator() const
			{
				LinkedListEnumerator<T>* result = new LinkedListEnumerator<T>(*this);
				return result;
			}
			template <typename T> friend class LinkedListEnumerator;
		private:
			int _size;
			
			/**
			* Returns a pointer to the node at the given index.  It tries to hop to the given
			* index by finding the best starting point (head or tail) in terms of the index number.
			* No error checking is performed since this is a private method, and hopefully the calling
			* methods did all the required checking.
			*/
			Node<T>* get_node(int in_index) const
			{
				Node<T>* result = NULL;
				if(in_index == 0)
					return _head;
				if(in_index == _size - 1)
					return _tail;

				// first see if we are closer to the head or the tail
				int head_distance = in_index;
				int tail_distance = _size - in_index;

				if(head_distance < tail_distance)	// closer to head
				{
					result = _head;
					for(int k = 0; k < in_index; k++)
						result = result->next;
				}
				else	// closer to tail
				{
					result = _tail;
					for(int k = _size - 1; k > in_index; k--)
						result = result->previous;
				}

				return result;
			}

			template<typename S> struct Node
			{
				Node* previous;
				Node* next;
				S value;

				Node(S in_value)
				{
					previous = NULL;
					next = NULL;
					value = in_value;
				}
			};

			Node<T>* _head;
			Node<T>* _tail;
		};

		template<typename T> class LinkedListEnumerator : public IEnumerator<T>
		{
		public:
			LinkedListEnumerator(const LinkedList<T>& in_linked_list)
			{
				_head = in_linked_list._head;
				_current = NULL;
			}
			bool moveNext()
			{
				if(_current == NULL)
				{
					if(_head == NULL)
						return false;
					_current = _head;
				}
				else
				{
					if(_current->next == NULL)
						return false;
					_current = _current->next;
				}
				return true;
			}
			T current() const
			{
				if(_current == NULL)
					throw Exception("Current node is NULL; you've reached the end of the LinkedList<T>");
				return _current->value;
			}
			void reset()
			{
				_current = NULL;
			}
		private:
			typename LinkedList<T>::Node<T>* _current;
			typename LinkedList<T>::Node<T>* _head;
		};
	}
}